export default function useSpeech() {
  const result = ref<null | string>(null)

  // 检查浏览器是否支持 Web Speech API
  if (!('webkitSpeechRecognition' in window)) {
    alert('您当前浏览器不支持语音输入！')
    return null
  }
  // 创建语音识别对象
  const recognition = new window.webkitSpeechRecognition()
  recognition.continuous = false // 不连续识别
  recognition.interimResults = false // 不返回中间结果
  recognition.lang = 'zh-CN' // 设置识别语言

  recognition.onresult = function (event) {
    result.value = event.results[0][0].transcript
  }
  recognition.onerror = function (event) {
    console.error('Speech recognition error', event.error)
  }
  function start() {
    recognition.start()
  }

  function stop() {
    recognition.stop()
  }

  return {
    start,
    stop,
    result,
  }
}
